package com.shigu.account.action;

import com.github.wxpay.extend.MyWxPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.shigu.MallResponse;
import com.shigu.account.api.VipManagerService;
import com.shigu.account.bo.AddCodeRequest;
import com.shigu.account.bo.ChangeLvRequest;
import com.shigu.account.service.InviteCodeService;
import com.shigu.exceptions.AdminException;
import com.shigu.weixin.service.PayApplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
 * create by  过儿  2019-06-10
 * 移动端的
 */
@RequestMapping("adminjson")
@Controller
public class VipAdminController {
    private static final Logger logger = LoggerFactory.getLogger(VipAdminController.class);

    @Resource(name = "vipManagerServiceImpl")
    VipManagerService vipManagerService;
    @Autowired
    PayApplyService payApplyService;
    @Autowired
    InviteCodeService inviteCodeService;

    @ResponseBody
    @RequestMapping("changeUserLevel")
    public MallResponse changeUserLevel(ChangeLvRequest request){
        vipManagerService.changeUserLevel(Long.valueOf(request.getUserId()),request.getLevel());
        return new MallResponse();
    }

    @ResponseBody
    @RequestMapping("addCode")
    public MallResponse addCode(AddCodeRequest request) throws AdminException {
        return inviteCodeService.addCode(request.getUserId(),request.getInviteCode());
    }


    //支付回调
    @RequestMapping("vipPayCallBack")
    public void payCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StringBuffer sb = new StringBuffer();
        String s;
        try {
            InputStream inputStream = request.getInputStream();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) {
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                }
            }
            inputStream.close();
        }catch (Exception e){
            logger.error( "" , e);
        }

        logger.error("====================vip支付回调参数：" + sb.toString());
        //jsapi 会返回 appId,根据appId去获取相应的商户 key. 做验签
        MyWxPayConfig config = new MyWxPayConfig();
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(sb.toString());  // 转换成map
//        ConfigMapper.getMchKey(notifyMap.get("app_id"));

        if (WXPayUtil.isSignatureValid(notifyMap, config.getKey(), WXPayConstants.SignType.MD5)) {
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            boolean success = payApplyService.dowithPayApply(notifyMap.get("return_code"),notifyMap.get("return_msg"),
                    notifyMap.get("total_fee"),notifyMap.get("transaction_id"),
                    notifyMap.get("out_trade_no"));
            //订单
            vipManagerService.userVipCallback(success,notifyMap.get("out_trade_no"));
            Map<String,String> dataMap=new HashMap<>();
            dataMap.put("return_code","SUCCESS");
            dataMap.put("return_msg","OK");
            PrintWriter writer=response.getWriter();
            writer.write(WXPayUtil.mapToXml(dataMap));
            writer.flush();
            writer.close();
        } else {
            // 签名错误，如果数据里没有sign字段，也认为是签名错误
            logger.error("非法请求："+sb.toString());
        }
    }
}
